package com.itheima.service;

import com.itheima.client.ClientPage;
import com.itheima.client.orderpojo.Vo.OrderDetails;
import com.itheima.client.orderpojo.Vo.OrderGetShoppingCartVo;
import com.itheima.client.orderpojo.Vo.OrderHistoryVo;
import com.itheima.client.orderpojo.Vo.OrderUserVo;
import com.itheima.client.orderpojo.dto.OrderDto;
import com.itheima.common.SnowFlake;
import com.itheima.common.TokenHolder;
import com.itheima.mapper.admin.OrderMapper;
import com.itheima.mapper.client.ClientOrderMapper;
import com.itheima.mapper.client.ShoppingCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author wuzhiyong
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ClientOrderService {
    @Autowired
    private ClientOrderMapper clientOrderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 提交订单
     *
     * @param orderDto orderDto
     * @return 条数>0
     */
    public boolean addOrder(OrderDto orderDto) {
        //获取订单编号
        long id = snowFlake.nextId();
        //获取订单号
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = simpleDateFormat.format(date);
        //获取userid
        String userId = TokenHolder.getCurrentId();
        //获取地址id
        String addressBookId = orderDto.getAddressBookId();
        //通过地址id获取用户信息
        OrderUserVo orderUserVo = clientOrderMapper.selectByUserId(addressBookId);
        //获取用户名
        String username = "user" + orderUserVo.getPhone();
        //获取手机号
        String phone = orderUserVo.getPhone();
        //获取地址
        String address = orderUserVo.getDetail();
        //获取收货人
        String consignee = orderUserVo.getConsignee();

        //获取购物车信息
        List<OrderGetShoppingCartVo> orderGetShoppingCartVos = clientOrderMapper.selectShoppingCart(userId);

        BigDecimal sumamount = new BigDecimal(0);
        if (orderGetShoppingCartVos == null) {
            return false;
        }
        for (OrderGetShoppingCartVo orderGetShoppingCartVo : orderGetShoppingCartVos) {
            if (orderGetShoppingCartVo == null) {
                continue;
            }

            //获取金额
            BigDecimal amount = orderGetShoppingCartVo.getAmount();
            //获取份数
            Integer number = orderGetShoppingCartVo.getNumber();
            BigDecimal numberm = new BigDecimal(number + "");
            //获取购物车中单一商品总金额
            BigDecimal sum = amount.multiply(numberm);
            //获取购物车总金额
            sumamount = sumamount.add(sum);

            //获取订单详情所需字段
            String name = orderGetShoppingCartVo.getName();
            long detailid = snowFlake.nextId();

            //组装订单详情实体并插入数据库
            OrderDetails orderDetails = new OrderDetails();
            orderDetails.setName(name);
            orderDetails.setNumber(orderGetShoppingCartVo.getNumber());
            orderDetails.setId(String.valueOf(detailid));
            orderDetails.setOrderId(String.valueOf(id));
            clientOrderMapper.insertOrderDetails(orderDetails);
        }
        //组装订单响应实体
        orderDto.setId(String.valueOf(id));
        orderDto.setNumber(format);
        orderDto.setUserId(userId);
        orderDto.setUserName(username);
        orderDto.setPhone(phone);
        orderDto.setAddress(address);
        orderDto.setOrderTime(new Date());
        orderDto.setCheckoutTime(new Date());
        orderDto.setAmount(sumamount);
        orderDto.setConsignee(consignee);
        //清空购物车
        shoppingCartMapper.deleteShoppingCart(userId);
        return clientOrderMapper.insertOrder(orderDto) > 0;
    }

    /**
     * 订单列表
     *
     * @param page     page
     * @param pageSize pagesize
     * @return ClientPage<OrderHistoryVo> ClientPage<OrderHistoryVo>
     */
    public ClientPage<OrderHistoryVo> getOrderPage(Integer page, Integer pageSize) {
        String userId = TokenHolder.getCurrentId();
        //获取索引
        int startIndex = (page - 1) * pageSize;
        //获取总条数
        int total = clientOrderMapper.selectAll(userId);
        //获取总页数

        BigDecimal totalBig = new BigDecimal(total);
        BigDecimal pageSizeBig = new BigDecimal(pageSize);
        int pages = (int) Math.ceil(totalBig.divide(pageSizeBig).doubleValue());
        //获取分页后内容
        List<OrderHistoryVo> historyVos = clientOrderMapper.selectOrderPage(userId, startIndex, pageSize);

        //组装分页实体
        ClientPage<OrderHistoryVo> orderpage = new ClientPage<>();

        orderpage.setSize(pageSize);
        orderpage.setCurrent(page);
        orderpage.setTotal(total);
        orderpage.setRecords(historyVos);
        orderpage.setPages(pages);

        return orderpage;
    }
}
